package com.ybzl.gateway.netty.decoder;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class YbzlDecoder extends ByteToMessageDecoder {
    private static final byte START_BYTE_1 = (byte) 0x59; // 开始符
    private static final byte START_BYTE_2 = (byte) 0x42; // 开始符
    private static final byte END_BYTE_1 = (byte) 0x5A;  // 结束符
    private static final byte END_BYTE_2 = (byte) 0x4C;  // 结束符

    // 59 43 00  5A 4C 59
    // 59 42 00  5A 4C 59
    // 42 00 5A 4C
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (!in.isReadable()) {
            return;
        }

        if (in.readableBytes() < 2){
            return;
        }

        if (in.getByte(in.readerIndex()) == START_BYTE_1 &&
                in.getByte(in.readerIndex() + 1) == START_BYTE_2) {
            int start = in.readerIndex();
            int end = in.indexOf(start, in.writerIndex(), END_BYTE_1);
            while (end != -1 && end + 1 < in.writerIndex() && in.getByte(end + 1) != END_BYTE_2) {
                end = in.indexOf(end + 2, in.writerIndex(), END_BYTE_1);// 就说明不等于
            }
            if (end == -1) {
                return;
            }
            int packetLength = end + 2 - start;
            out.add(in.readSlice(packetLength).retain());
            in.readerIndex(end + 2);
        } else {
            in.readByte();// 修改了指针
        }
    }
}